<template>
  <div class="organization page_set">
    <a-layout>
      <a-layout-sider class="border-right">
        <div class="search-box-padding">
          <a-input-search v-model="searchParams" placeholder="搜索部门" @search="onSearch" />
        </div>
        <div class="orgin-title" :class="active == 'active' ? 'active ' : ''" @click="reloadData">
          <img src="../../assets/icons/icon1.png" style="width: 18px; height: 18px" alt="" />
          <span class="organization-left-name">{{ companyName }}</span>
          <a-icon type="reload" :class="rotate ? 'rotate-a' : 'rotate-b'" @click="refushIcon" />
        </div>
        <a-tree
          :defaultSelectedKeys="[selectedKeys]"
          show-icon
          default-expand-all
          :tree-data="dataList"
          :expanded-keys="expandedKeys"
          :autoExpandParent="autoExpandParent"
          :blockNode="true"
          :showIcon="true"
          @expand="onExpand"
          @select="onSelect"
        >
          <template slot="title" slot-scope="{ title }">
            <span v-if="title.indexOf(searchValue) > -1">
              {{ title.substr(0, title.indexOf(searchValue)) }}
              <span style="color: #f50">
                <img slot="floder" src="../../assets/icons/icon2.png" style="width: 15px; height: 15px" alt="" />
                {{ searchValue }}
              </span>
              {{ title.substr(title.indexOf(searchValue) + searchValue.length) }}
            </span>
            <span v-else>{{ title }}</span>
          </template>
        </a-tree>
      </a-layout-sider>
      <a-layout class="pt24 pl24 bgc-white">
        <div class="pb24">
          <a-row>
            <span class="h1">{{ depName }}</span>
            <span class="tag-btn">{{ type === "2" ? "部门" : "公司" }}</span>
            <a-button size="small" @click="setDrawer(depName)">设置</a-button>
          </a-row>
          <a-row>{{ desc }}</a-row>
        </div>
        <a-layout-content v-if="page">
          <a-tabs :default-active-key="page" @change="changeTab">
            <a-tab-pane key="1" :tab="`成员管理`">
              <member
                v-if="page == 1"
                ref="member"
                :selected-id="selectedKeys"
                :company="isCompany"
                v-on="$listeners"
                @dataLength="dataLength($event)"
                @hasChanged="hasChanged($event)"
                @initData="initData"
                @refush="refush"
              />
            </a-tab-pane>
            <a-tab-pane key="2" tab="部门管理">
              <department
                v-if="page == 2"
                :company="isCompany"
                :selected-id="selectedKeys"
                :level="level"
                @refreshList="onRefresList"
                @getTree="getTreeList"
                @updateDep="onUpdateDep"
              />
            </a-tab-pane>
          </a-tabs>
        </a-layout-content>
      </a-layout>
    </a-layout>
    <a-drawer title="编辑" :width="720" :visible="visibleCompany" :wrap-style="{ overflow: 'auto' }" @close="visibleCompany = false">
      <a-form :form="formCom" layout="vertical" @submit="handleCompanySubmit">
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="公司名称">
              <a-input
                v-decorator="[
                  'name',
                  {
                    rules: [{ required: true, message: '请输入公司名称' }]
                  }
                ]"
                placeholder="请输入公司名称"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="官网地址">
              <a-input v-decorator="['officialWebsite']" addon-before="https://" placeholder="请输入公司网址" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="公司地址">
              <a-input v-decorator="['address']" placeholder="请输入公司地址" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="公司法人">
              <a-input v-decorator="['legalPerson']" placeholder="请输入公司法人" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="法人联系方式">
              <a-input v-decorator="['telephone']" placeholder="请输入联系方式" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="联系邮箱">
              <a-input v-decorator="['email']" placeholder="请输入邮箱" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="公司规模">
              <a-select v-decorator="['personSize']" placeholder="请选择人数">
                <a-select-option v-for="(item, index) in person" :key="index" :value="item">{{ item }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="所在行业">
              <a-select v-decorator="['industry']" placeholder="请选择行业">
                <a-select-option v-for="(item, index) in industry" :key="index" :value="item">{{ item }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="公司简介">
              <a-textarea v-decorator="['profile']" placeholder="请输入" :rows="4" />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item>
              <a-input v-decorator="['id']" type="hidden" />
            </a-form-item>
          </a-col>
        </a-row>
        <div class="drawer-footer-box">
          <a-button :style="{ marginRight: '12px' }" @click="visibleCompany = false">取消</a-button>
          <a-button type="primary" html-type="submit">确定</a-button>
        </div>
      </a-form>
    </a-drawer>
    <a-drawer :title="title" :width="520" :visible="visible" :wrap-style="{ overflow: 'auto' }" @close="onClose">
      <a-form :form="formSetting" layout="vertical" @submit="handleSubmit">
        <a-row :gutter="16">
          <a-col :span="24">
            <a-form-item label="名称">
              <a-input
                v-decorator="[
                  'name',
                  {
                    rules: [{ required: true, message: '请输入名称' }]
                  }
                ]"
                placeholder="请输入名称"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="24">
            <a-form-item label="简介">
              <a-textarea v-decorator="['desc']" placeholder="请输入" :rows="4" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="24">
            <a-form-item>
              <a-input v-decorator="['id']" type="hidden" />
            </a-form-item>
          </a-col>
        </a-row>

        <div class="drawer-footer-box">
          <a-button :style="{ marginRight: '12px' }" @click="delDep"> 删除</a-button>
          <a-button :style="{ marginRight: '12px' }" @click="onClose"> 取消</a-button>
          <a-button type="primary" html-type="submit">确定</a-button>
        </div>
      </a-form>
    </a-drawer>
  </div>
</template>

<script>
import { getDepAndEmpInfo, getDepInfosById, putDepartment, delDepartments } from "@/api/department/department";
import member from "./member";
import department from "./department";
import { getCompanies, putCompanies, getSelectDepTree } from "@/api/company";
import { mapState } from "vuex";

export default {
  components: { member, department },
  data() {
    return {
      checkedKeys: [],
      rotate: false,
      // 查询参数
      userNum: 0,
      searchParams: "",
      childChanged: false,
      isCompany: true,
      localSelectId: "",
      page: null,
      type: "1",
      active: "active",
      comId: "",
      title: "",
      selectedKeys: "",
      level: 3,
      comParentId: "",
      companyId: "",
      depName: "",
      profile: "",
      desc: "",
      companyName: "",
      expandedKeys: [],
      searchValue: "",
      autoExpandParent: true,
      dataList: [],
      formSetting: this.$form.createForm(this),
      formCom: this.$form.createForm(this),
      visible: false,
      visibleCompany: false,
      form: {},
      person: ["0-20", "20-99", "99-200", "200-500", "500-1000", "1000人以上"],
      industry: [
        "互联网/信息技术",
        "教育行业",
        "制造业",
        "贸易/批发/零售",
        "房地产业",
        "建筑业",
        "金融业",
        "服务业",
        "社会组织",
        "科研服务",
        "公共/环境",
        "居民服务",
        "开采业",
        "农林牧渔",
        "电/热/燃气/水供应",
        "运输/物流/仓储",
        "文体/娱乐/传媒",
        "商业服务/租赁",
        "医疗医药",
        "政府/事业单位"
      ]
    };
  },
  computed: {
    ...mapState(["hr"])
  },
  created() {
    const page = this.$route.query.page;
    if (page === "department") {
      this.page = "2";
    } else {
      this.page = "1";
    }
    this.depName = this.hr.companyName;
    getCompanies({ name: this.$store.state.hr.companyName }).then((res) => {
      this.profile = res.data.entities[0].profile;
      this.desc = res.data.entities[0].profile;
    });

    this.getTreeList();
  },

  methods: {
    onUpdateDep(id, parentId) {
      this.expandedKeys = [...this.expandedKeys, parentId];
      this.refush();
    },
    /* 代码重构  */
    // 获取左侧树结构
    async getTreeList() {
      const { data } = await getSelectDepTree({
        companyId: this.$store.state.hr.companyId
      });
      if (!this.selectedKeys) {
        this.selectedKeys = data[0].id;
        this.localSelectId = data[0].id;
        this.companyName = data[0].name;
      }
      this.dataList = this.tree(data[0].depChildList, "depChildList");
    },
    // 返回子组件触发事件
    hasChanged(e) {
      this.childChanged = e;
      this.getTreeList();
    },
    dataLength(e) {
      this.userNum = e;
    },

    /* 代码重构  */

    handleCompanySubmit(e) {
      e.preventDefault();
      this.formCom.validateFields((err, values) => {
        if (!err) {
          values.id = this.$store.state.hr.companyId;
          putCompanies(values).then((res) => {
            this.$notification["success"]({
              message: "success",
              description: "修改成功"
            });
            this.visibleCompany = false;

            this.desc = values.profile;
            this.profile = values.profile;
            this.depName = values.name;

            this.$store.dispatch("onCompanyClick", {
              id: values.id,
              name: values.name
            });

            location.reload();
          });
        }
      });
    },
    onRefresList(e) {
      this.dataList = this.tree(e, "depChildList");
    },
    changeTab(page) {
      this.page = page;
    },
    handleSubmit(e) {
      e.preventDefault();
      this.formSetting.validateFields((err, values) => {
        if (!err) {
          values.type = this.form.type;
          values.sort = this.form.sort;
          values.parentId = this.form.parentId;
          values.companyId = this.form.companyId;
          values.virural = this.form.virural;
          values.level = this.form.level;
          putDepartment(values).then((res) => {
            this.$notification["success"]({
              message: "success",
              description: "修改成功"
            });
            this.visible = false;
            this.childChanged = true;
            this.desc = values.desc;
            this.depName = values.name;
            // 刷新左侧数据
            this.refush();
          });
        }
      });
    },
    onClose() {
      this.visible = false;
    },
    setDrawer(name) {
      if (this.type === "2") {
        this.visible = true;
        this.title = "编辑";

        const that = this;

        setTimeout(() => {
          this.formSetting.setFieldsValue({
            id: that.selectedKeys,
            name: that.depName,
            desc: that.desc
          });
        }, 100);

        getDepAndEmpInfo(this.hr.companyId, { depName: name }).then((res) => {
          if (res.data && res.data.length === 0) {
            return false;
          }
          this.form = res.data[0];
        });
      } else {
        this.visibleCompany = true;

        getCompanies({ name: this.$store.state.hr.companyName }).then((res) => {
          const e = res.data.entities[0];
          this.formCom.setFieldsValue({
            address: e.address,
            email: e.email,
            id: e.id,
            legalPerson: e.legalPerson,
            name: e.name,
            officialWebsite: e.officialWebsite,
            telephone: e.telephone,
            personSize: e.personSize,
            profile: e.profile,
            industry: e.industry
          });
        });
      }
    },
    tree(array, childKey, onlyLastChild) {
      if (!array) {
        return [];
      }
      array.map((item, index) => {
        item["value"] = item.id;
        item["key"] = item.id;
        item["slots"] = {
          icon: "floder"
        };

        item["title"] = item.name + "（" + item.empDirectCount + "）";
        item["children"] = item[childKey];

        if (item.children) {
          item["disabled"] = onlyLastChild;
          this.tree(item.children, childKey, onlyLastChild);
        }
      });
      return array;
    },
    refush() {
      this.getTreeList();
    },
    refushIcon() {
      this.rotate = !this.rotate;
      this.getTreeList();
    },
    reloadData() {
      this.isCompany = true;
      this.type = "1";
      this.active = "active";
      this.level = 3;
      this.selectedKeys = this.localSelectId;
      this.hr.companyName = this.$store.state.hr.companyName;

      this.depName = this.hr.companyName;
      this.desc = this.profile;
      // this.getData(this.comId)
    },
    getData(id) {
      getDepInfosById(id, { companyId: this.hr.companyId }).then((res) => {
        this.depName = res.data.name;
        this.desc = res.data.desc;
      });
    },
    onSearch(depName) {
      this.searchParams = depName;
      this.initData(depName);
    },
    initData(depName) {
      getSelectDepTree({ companyId: this.hr.companyId, depName }).then((res) => {
        if (res.data && res.data.length === 0) {
          return this.$warning({
            title: "查找提示",
            content: "没有查到该部门",
            onOk: () => {
              this.searchParams = "";
            }
          });
        } else {
          if (depName) {
            this.selectedKeys = res.data[0].parentId;
            this.comId = res.data[0].parentId;
            this.dataList = this.tree(res.data, "depChildList");
          } else {
            this.selectedKeys = res.data[0].depChildList[0].parentId;
            this.comId = res.data[0].depChildList[0].parentId;
            this.dataList = this.tree(res.data[0].depChildList, "depChildList");
          }
        }
      });
    },
    onExpand(expandedKeys) {
      this.expandedKeys = expandedKeys;
      this.autoExpandParent = false;
    },
    onCheck(checkedKeys) {
      this.checkedKeys = checkedKeys;
    },
    onSelect(selectedKeys, info) {
      // 选中才更改
      if (info.selected) {
        this.isCompany = false;
        this.type = "2";
        this.getData(selectedKeys[0]);
        this.active = "tree";
        this.selectedKeys = selectedKeys[0];
        this.level = info.node.dataRef.level + 1;
      }
    },
    delDep() {
      var that = this;
      this.$confirm({
        title: `确定删除部门 ${this.depName}吗`,
        onOk() {
          delDepartments([that.selectedKeys]).then((res) => {
            that.$notification["success"]({
              message: "success",
              escription: "删除成功"
            });
            location.reload();
          });
        }
      });
    }
  }
};
</script>

<style scoped lang="scss">
.ant-layout-sider {
  min-height: calc(100vh - 152px);
}

.ant-tree-treenode-switcher-close {
  border-bottom: 1px solid #e8e8e8;
  height: 40px;
  padding-top: 7px;
  width: 100%;
}

.organization {
  ::v-deep .border-right {
    flex: 0 0 auto !important;
    max-width: none !important;
    min-width: 201px !important;
    width: min-content !important;
    border-right: 1px solid #ccc !important;
    .rotate-a {
      transition: all 1s;
      -moz-transition: all 1s; /* Firefox 4 */
      -webkit-transition: all 1s; /* Safari and Chrome */
      -o-transition: all 2s; /* Opera */
    }

    .rotate-b {
      transform: rotate(-180deg);
      -ms-transform: rotate(-180deg); /* Internet Explorer */
      -moz-transform: rotate(-180deg); /* Firefox */
      -webkit-transform: rotate(-180deg); /* Safari 和 Chrome */
      -o-transform: rotate(-180deg); /* Opera */
      transition: all 1s;
      -moz-transition: all 1s; /* Firefox 4 */
      -webkit-transition: all 1s; /* Safari and Chrome */
      -o-transition: all 1s; /* Opera */
    }
  }

  .ant-layout {
    background: #fff;
  }
  .search-box-padding {
    padding: 24px 20px;
  }
  .active {
    background: var(--primary);
    color: #fff;
  }
  .orgin-title {
    .organization-left-name {
      text-overflow: ellipsis;
      overflow: hidden;
      width: 150px;
      white-space: nowrap;
      display: inline-block;
      margin-left: 5px;
    }
    padding-left: 5px;
    display: flex;
    align-items: center;
    cursor: pointer;
    height: 40px;
    line-height: 40px;
    position: relative;
    .anticon-deployment-unit {
      padding-left: 12px;
      padding-right: 3px;
    }
    .anticon-reload {
      position: absolute;
      right: 10px;
      top: 12px;
    }
  }
  .tree {
    >>> .ant-tree-treenode-selected {
      background: var(--primary);
      color: #fff;
      width: 100%;
      .ant-tree-node-selected {
        color: #fff;
        background: none;
        width: 100%;
      }
    }
  }

  .h1 {
    font-size: 20px;
    color: #333;
    margin-right: 4px;
  }

  .tag-btn {
    font-size: 12px;
    padding: 2px 4px;
    color: #fff;
    background: var(--primary);
    border-radius: 4px;
    margin-right: 10px;
  }
}

.architecture {
  width: 100%;
  background: white;
}

.organization >>> .ant-tabs-tab-active {
  color: #6a66f6 !important;
}

.organization >>> .ant-tabs-tab:hover {
  color: #6a66f6 !important;
}

.organization >>> .ant-tabs-ink-bar {
  background-color: var(--primary);
}

.topOrganization {
  height: 40px;
  line-height: 40px;
  border-bottom: 1px solid #ebeef5;
}

.positionAdd {
  position: relative;
  left: 46%;
  margin-top: 35vh;
  .note {
    font-size: 16px;
    margin: 15px 0;
  }
  button {
    height: 45px;
  }
}
</style>
